//
//  SinglePlayer.m
//  ShootBall
//
//  Created by macpro on 4/28/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "SinglePlayer.h"
#import "Ball.h"
#import "MenuGame.h"
#import "Bump.h"
#import "Banana.h"

#define PTM_RATIO 32

@interface SinglePlayer (Private) 
-(void)initBox2dWorld;
-(void) enableBox2dDebugDrawing;
@end

@implementation SinglePlayer

-(void) fadeInLabel:(CCLabelTTF *) lb{
    [lb runAction:[CCSequence actions:[CCFadeIn actionWithDuration:0.5],[CCCallFuncO actionWithTarget:self selector:@selector(fadeOutLabel:) object:lb], nil]];
}

-(void) fadeOutLabel:(CCLabelTTF *) lb{
    [lb runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFuncO actionWithTarget:self selector:@selector(fadeInLabel:) object:lb], nil]];
}

+(id) scene
{
	CCScene *scene = [CCScene node];
	SinglePlayer *layer = [SinglePlayer node];
	[scene addChild: layer];
	return scene;
}

-(void) goHome{
    [btnGoHome removeFromSuperview];
    [btnGoHome release];
    btnGoHome = nil;
    [[CCDirector sharedDirector] replaceScene:[CCTransitionMoveInL transitionWithDuration:0.5 scene:[MenuGame scene]]];
}

-(void) addHomeButton{
    btnGoHome = [[UIButton alloc] initWithFrame:CGRectMake(682, 50, 118, 38)];
    [btnGoHome setImage:[UIImage imageNamed:@"restart_btn.png"] forState:UIControlStateNormal];
    btnGoHome.transform = CGAffineTransformMakeRotation(M_PI/2);
    [btnGoHome addTarget:self action:@selector(goHome) forControlEvents:UIControlEventTouchUpInside];
    [[[CCDirector sharedDirector] openGLView] addSubview:btnGoHome];
}

-(id) init
{
	if( (self=[super init] )) {
        
		CCSprite *background = [CCSprite spriteWithFile:@"background_game.jpg"];
		CGSize winSize = [[CCDirector sharedDirector] winSize];
		
		background.position = ccp(winSize.width/2, winSize.height/2);
		[self addChild: background];
		
        [self initBox2dWorld];
        
        // a bright background is desireable for this pinball table
		CCLayerColor* colorLayer_top = [CCLayerColor layerWithColor:ccc4(255, 255, 255, 200)];
        colorLayer_top.contentSize = CGSizeMake(1024, 60);
        colorLayer_top.position = ccp(0,winSize.height-60);
		[self addChild:colorLayer_top z:1];
        
        CCLayerColor* colorLayer_bottom = [CCLayerColor layerWithColor:ccc4(255, 255, 255, 200)];
        colorLayer_bottom.contentSize = CGSizeMake(1024, 60);
        colorLayer_bottom.position = ccp(0,0);
		[self addChild:colorLayer_bottom z:1];
        
        [self performSelector:@selector(addHomeButton) withObject:nil afterDelay:0.5];
        
        lb_score_1 = [[CCLabelTTF alloc] initWithString:@"Score: 0" dimensions:CGSizeMake(200, 60) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lb_score_1.color = ccBLUE;
        lb_score_1.position = ccp(1024-120,20);
        [self addChild:lb_score_1 z:2];
        
        CCLabelTTF *lb_player_1 = [[CCLabelTTF alloc] initWithString:@"Player 1:" dimensions:CGSizeMake(200, 60) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lb_player_1.color = ccBLUE;
        lb_player_1.position = ccp(240,20);
        [self addChild:lb_player_1 z:2];
        
        lbMove1 = [[CCLabelTTF alloc] initWithString:@"Move" dimensions:CGSizeMake(200, 60) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lbMove1.color = ccBLUE;
        lbMove1.position = ccp(570,20);
        lbMove1.visible = NO;
        [self addChild:lbMove1 z:2];
        
        lb_score_2 = [[CCLabelTTF alloc] initWithString:@"Score: 0" dimensions:CGSizeMake(200, 60) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lb_score_2.color = ccRED;
        lb_score_2.position = ccp(1024-120,768-40);
        [self addChild:lb_score_2 z:2];
        
        CCLabelTTF *lb_player_2 = [[CCLabelTTF alloc] initWithString:@"Player 2:" dimensions:CGSizeMake(200, 60) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lb_player_2.color = ccRED;
        lb_player_2.position = ccp(240,768-40);
        [self addChild:lb_player_2 z:2];
        
        lbMove2 = [[CCLabelTTF alloc] initWithString:@"Move" dimensions:CGSizeMake(200, 60) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lbMove2.color = ccRED;
        lbMove2.position = ccp(570,768-40);
        lbMove2.visible = NO;
        [self addChild:lbMove2 z:2];
        
        lbWinUser = [[CCLabelTTF alloc] initWithString:@"Blue Win" dimensions:CGSizeMake(200, 40) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lbWinUser.color = ccBLUE;
        lbWinUser.position = ccp(winSize.width/2, winSize.height/2);
        lbWinUser.visible = NO;
        lbWinUser.scale = 0.1;
        [self addChild:lbWinUser z:2];
        
        b1 = [CCSprite spriteWithFile:@"blue_ball.png"];
        b1.position = ccp(340,30);
        b1.visible = NO;
        b1.scale = 0.5;
        [self addChild:b1 z:2];
        
        b2 = [CCSprite spriteWithFile:@"blue_ball.png"];
        b2.position = ccp(380,30);
        b2.visible = NO;
        b2.scale = 0.5;
        [self addChild:b2 z:2];
        
        b3 = [CCSprite spriteWithFile:@"blue_ball.png"];
        b3.position = ccp(420,30);
        b3.visible = NO;
        b3.scale = 0.5;
        [self addChild:b3 z:2];
        
        br1 = [CCSprite spriteWithFile:@"red_ball.png"];
        br1.position = ccp(340,768-30);
        br1.visible = NO;
        br1.scale = 0.5;
        [self addChild:br1 z:2];
        
        br2 = [CCSprite spriteWithFile:@"red_ball.png"];
        br2.position = ccp(380,768-30);
        br2.visible = NO;
        br2.scale = 0.5;
        [self addChild:br2 z:2];
        
        br3 = [CCSprite spriteWithFile:@"red_ball.png"];
        br3.position = ccp(420,768-30);
        br3.visible = NO;
        br3.scale = 0.5;
        [self addChild:br3 z:2];
        
        currentBlueMark = 0;
        currentRedMark = 0;
        
        currentScore1 = 0;
        currentScore2 = 0;
        
        stopGame = NO;
        
        [self setupAll];
        
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
        
        [self scheduleUpdate];
	}
	return self;
}

-(void)setupAll {
    countRed = 0;
    countBlue = 0;
    
    if (currentBlueMark==currentRedMark && currentRedMark==0) {
        moveFirst = 1;
    }
    if (currentBlueMark==0) {
        for (int i=0; i<7; i++) {
            Ball* ballB = [Ball ballWithWorld:world at:ccp(200 + 100*i, 90) touchable:YES type:1];
            ballB.tag = i + 1;
            [self addChild:ballB z:2];
        }
    }
    else if (currentBlueMark==1) {
        for (int i=0; i<6; i++) {
            Ball* ballB = [Ball ballWithWorld:world at:ccp(250 + 100*i, 190) touchable:YES type:1];
            ballB.tag = i + 1;
            [self addChild:ballB z:2];
        }
        
        Ball* ballB7 = [Ball ballWithWorld:world at:ccp(2000, 2000) touchable:YES type:1];
        ballB7.tag = 7;
        ballB7.visible = NO;
        [self addChild:ballB7 z:2];
    }
    else if (currentBlueMark==2) {
        for (int i=0; i<5; i++) {
            Ball* ballB = [Ball ballWithWorld:world at:ccp(300 + 100*i, 290) touchable:YES type:1];
            ballB.tag = i + 1;
            [self addChild:ballB z:2];
        }
        
        Ball* ballB6 = [Ball ballWithWorld:world at:ccp(2000, 2000) touchable:YES type:1];
        ballB6.tag = 6;
        ballB6.visible = NO;
        [self addChild:ballB6 z:2];
        
        Ball* ballB7 = [Ball ballWithWorld:world at:ccp(2000, 2000) touchable:YES type:1];
        ballB7.tag = 7;
        ballB7.visible = NO;
        [self addChild:ballB7 z:2];
    }
    
    if (currentRedMark==0) {
        for (int i=0; i<7; i++) {
            Ball* ballR = [Ball ballWithWorld:world at:ccp(200 + 100*i, 680) touchable:YES type:2];
            ballR.tag = i + 8;
            [self addChild:ballR z:2];
        }
    }
    else if (currentRedMark==1) {
        for (int i=0; i<6; i++) {
            Ball* ballR = [Ball ballWithWorld:world at:ccp(250 + 100*i, 580) touchable:YES type:2];
            ballR.tag = i + 8;
            [self addChild:ballR z:2];
        }
        
        Ball* ballR7 = [Ball ballWithWorld:world at:ccp(-1000, -1000) touchable:YES type:2];
        ballR7.tag = 14;
        ballR7.visible = NO;
        [self addChild:ballR7 z:2];
    }
    else if (currentRedMark==2) {
        for (int i=0; i<5; i++) {
            Ball* ballR = [Ball ballWithWorld:world at:ccp(300 + 100*i, 480) touchable:YES type:2];
            ballR.tag = i + 8;
            [self addChild:ballR z:2];
        }
        
        Ball* ballR6 = [Ball ballWithWorld:world at:ccp(-1000, -1000) touchable:YES type:2];
        ballR6.tag = 13;
        ballR6.visible = NO;
        [self addChild:ballR6 z:2];
        
        Ball* ballR7 = [Ball ballWithWorld:world at:ccp(-1000, -1000) touchable:YES type:2];
        ballR7.tag = 14;
        ballR7.visible = NO;
        [self addChild:ballR7 z:2];
    }
    
    Bump* bump1 = [Bump bumpInWorld:world at:ccp(200, 400)];
    bump1.tag = 20;
    bump1.visible = YES;
    [self addChild:bump1 z:2];
    
    Bump* bump2 = [Bump bumpInWorld:world at:ccp(400, 300)];
    bump2.tag = 21;
    bump2.visible = YES;
    [self addChild:bump2 z:2];
    
    Bump* bump3 = [Bump bumpInWorld:world at:ccp(700, 500)];
    bump3.tag = 22;
    bump3.visible = YES;
    [self addChild:bump3 z:2];
    
    
    Banana* bana1 = [Banana bananaInWorld:world at:ccp(290, 400)];
    bana1.tag = 23;
    [self addChild:bana1 z:2];
    
    NSMutableArray* ary = [[[NSMutableArray alloc] init] autorelease];
    for (CCNode* node in self.children) {
        if ([node isKindOfClass:[Ball class]]) {
            [ary addObject:node];
        }
    }
    for (CCNode* ball in ary) {
        ((Ball *) ball).moveUser = moveFirst;
    }
    
    if (moveFirst==1) {
        lbMove1.visible = YES;
        lbMove2.visible = NO;
        [lbMove1 runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFuncO actionWithTarget:self selector:@selector(fadeInLabel:) object:lbMove1], nil]];
    }
    else if (moveFirst==2) {
        lbMove1.visible = NO;
        lbMove2.visible = YES;
        [lbMove2 runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFuncO actionWithTarget:self selector:@selector(fadeInLabel:) object:lbMove2], nil]];
    }
    
    hadChangeLabel = YES;
    stopGame = NO;
}

-(void)dealloc {
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super dealloc];
}

-(void) initBox2dWorld
{
	// Construct a world object, which will hold and simulate the rigid bodies.
	b2Vec2 gravity = b2Vec2(0.0f, 0.0f);
	bool allowBodiesToSleep = true;
	world = new b2World(gravity, allowBodiesToSleep);
	
	contactListener = new ContactListener();
	world->SetContactListener(contactListener);
	
	// Define the static container body, which will provide the collisions at screen borders.
	b2BodyDef containerBodyDef;
	b2Body* containerBody = world->CreateBody(&containerBodyDef);
	
	// for the ground body we'll need these values
	CGSize screenSize = [CCDirector sharedDirector].winSize;
	float widthInMeters = screenSize.width / PTM_RATIO;
	float heightInMeters = screenSize.height / PTM_RATIO;
	b2Vec2 lowerLeftCorner = b2Vec2(0, 0);
	b2Vec2 lowerRightCorner = b2Vec2(widthInMeters, 0);
	b2Vec2 upperLeftCorner = b2Vec2(0, heightInMeters);
	b2Vec2 upperRightCorner = b2Vec2(widthInMeters, heightInMeters);
	
	// Create the screen box' sides by using a polygon assigning each side individually.
	b2PolygonShape screenBoxShape;
	
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &screenBoxShape;
    fixtureDef.density = 1.0f;
    fixtureDef.restitution = 1.0f;
    fixtureDef.friction = 1.0f;
    
    //left side
    screenBoxShape.SetAsEdge(upperLeftCorner, lowerLeftCorner);
    containerBody->CreateFixture(&fixtureDef);
    	
    //right side
    screenBoxShape.SetAsEdge(upperRightCorner, lowerRightCorner);
    containerBody->CreateFixture(&fixtureDef);
    
    // top
    screenBoxShape.SetAsEdge(upperLeftCorner, upperRightCorner);
    containerBody->CreateFixture(&fixtureDef);
    	
    // bottom
    screenBoxShape.SetAsEdge(lowerLeftCorner, lowerRightCorner);
    containerBody->CreateFixture(&fixtureDef);
}

-(void) hideLabelWin{
    lbWinUser.visible = NO;
    lbWinUser.scale = 0.1;
}

-(void) doMarkGame:(int) markType{
    if (markType==1) {
        currentBlueMark++;
        if (currentBlueMark==1) {
            b1.visible = YES;
            b2.visible = NO;
            b3.visible = NO;
        }
        else if (currentBlueMark==2) {
            b1.visible = YES;
            b2.visible = YES;
            b3.visible = NO;
        }
        else if (currentBlueMark==3) {
            b1.visible = YES;
            b2.visible = YES;
            b3.visible = YES;
        }
        moveFirst = 2;
        
        [lbWinUser setString:@"Blue Win"];
        lbWinUser.color = ccBLUE;
        lbWinUser.visible = YES;
        
        [lbWinUser runAction:[CCSequence actions:[CCSpawn actions:[CCScaleTo actionWithDuration:1.5 scale:5],[CCFadeOut actionWithDuration:1.5], nil],[CCCallFunc actionWithTarget:self selector:@selector(hideLabelWin)], nil]];
    }
    else {
        currentRedMark++;
        if (currentRedMark==1) {
            br1.visible = YES;
            br2.visible = NO;
            br3.visible = NO;
        }
        else if (currentRedMark==2) {
            br1.visible = YES;
            br2.visible = YES;
            br3.visible = NO;
        }
        else if (currentRedMark==3) {
            br1.visible = YES;
            br2.visible = YES;
            br3.visible = YES;
        }
        moveFirst = 1;
        
        [lbWinUser setString:@"Red Win"];
        lbWinUser.color = ccRED;
        lbWinUser.visible = YES;
        [lbWinUser runAction:[CCSequence actions:[CCSpawn actions:[CCScaleTo actionWithDuration:1.5 scale:5],[CCFadeOut actionWithDuration:1.5], nil],[CCCallFunc actionWithTarget:self selector:@selector(hideLabelWin)], nil]];
    }
    
    if (currentBlueMark==3) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over" message:@"Blue ball is WINNER!!!" delegate:self cancelButtonTitle:@"Home" otherButtonTitles:@"Try Again", nil];
        [alert show];
        [alert release];
    }
    if (currentRedMark==3) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over" message:@"Red ball is WINNER!!!" delegate:self cancelButtonTitle:@"Home" otherButtonTitles:@"Try Again", nil];
        [alert show];
        [alert release];
    }
}

-(void) resetAllBall{
    NSMutableArray* ary = [[[NSMutableArray alloc] init] autorelease];
    for (CCNode* node in self.children) {
        if ([node isKindOfClass:[Ball class]]) {
            [ary addObject:node];
        }
    }
    for (CCNode* ball in ary) {
        [ball stopAllActions];
        [(Ball *) ball removeTouchDelete];
        [self removeChild:ball cleanup:YES];
    }
    [self setupAll];
}

-(void) resetGameScreen{
    [self resetAllBall];
    stopGame = NO;
}

-(void) stopMoving:(int) tag{
    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *tempSprite = (CCSprite *) b->GetUserData();
            if (tempSprite.tag==tag) {
                b->SetLinearVelocity(b2Vec2(0.0f, 0.0f));
                b->SetAngularVelocity(0.0f);
                
                for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) {
                    b->DestroyFixture(f);
                }
                break;
            }
        }        
    }
}

-(void) endMovingWithTag:(int) tag{
    NSMutableArray* ary = [[[NSMutableArray alloc] init] autorelease];
    for (CCNode* node in self.children) {
        if ([node isKindOfClass:[Ball class]]) {
            [ary addObject:node];
        }
    }
    
    NSLog(@"1 move:%d, tag:%d",moveFirst,tag);
    
    if (moveFirst==1 && tag<=7) {
        moveFirst = 2;
        
        for (CCNode* ball in ary) {
            ((Ball *) ball).moveUser = moveFirst;
        }
    }
    else if (moveFirst==2 && tag>7) {
        moveFirst = 1;
        
        for (CCNode* ball in ary) {
            ((Ball *) ball).moveUser = moveFirst;
        }
    }
    
    NSLog(@"2 move:%d, tag:%d",moveFirst,tag);
    
    hadChangeLabel = NO;
}

-(void) checkAndEndMoving{
    if ([self checkBallNotMove]) {
        [self endMovingWithTag:currentTouchTag];
        [self unschedule:@selector(checkAndEndMoving)];
    }
}

-(void) stopBall:(Ball *) ball{
    [self stopMoving:ball.tag];
    
    if (ball.tag==currentTouchTag) {
        [self schedule:@selector(checkAndEndMoving)];
        currentTouchTag = ball.tag;
    }
    [self removeChild:ball cleanup:YES];
}

-(void) update:(ccTime)delta
{
    if (stopGame) {
        return;
    }
    
    if ([self checkBallNotMove] && !hadChangeLabel) {
        [lbMove1 stopAllActions];
        [lbMove2 stopAllActions];
        if (moveFirst==1) {
            lbMove1.visible = YES;
            lbMove2.visible = NO;
            [lbMove1 runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFuncO actionWithTarget:self selector:@selector(fadeInLabel:) object:lbMove1], nil]];
        }
        else if (moveFirst==2) {
            lbMove1.visible = NO;
            lbMove2.visible = YES;
            [lbMove2 runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFuncO actionWithTarget:self selector:@selector(fadeInLabel:) object:lbMove2], nil]];
        }
        
        hadChangeLabel = YES;
    }
    
    for (CCNode* node in [self children]) {
        if ([node isKindOfClass:[Ball class]]) {
            Ball* ball = (Ball*)node;
            if (ball.isInHall && ball!=nil && ball.visible) {
                ball.visible = NO;
                [self performSelector:@selector(stopBall:) withObject:ball afterDelay:0.0];
                
                if (ball.tag<=7) {
                    currentScore2+=10;
                }
                else if (ball.tag>7) {
                    currentScore1+=10;
                }
                
                [lb_score_1 setString:[NSString stringWithFormat:@"Score: %d",currentScore1]];
                [lb_score_2 setString:[NSString stringWithFormat:@"Score: %d",currentScore2]];
            }
        }
    }
    
    int count1 = 0;
    int count2 = 0;
    for (CCNode* node in [self children]) {
        if ([node isKindOfClass:[Ball class]]) {
            Ball* ball = (Ball*)node;
            if (ball.visible) {
                if (ball.tag<=7) {
                    count1++;
                }
                else if (ball.tag>7) {
                    count2++;
                }
            }
        }
    }
    
    countBlue = 7 - count1;
    countRed = 7 - count2;
    
    //NSLog(@"countBlue:%d, countRed:%d",countBlue,countRed);
    
    if (countBlue==7) {
        NSLog(@"blue close");
        [self doMarkGame:2];
        stopGame = YES;
        
        currentScore2+=count2*10;
        
        [lb_score_1 setString:[NSString stringWithFormat:@"Score: %d",currentScore1]];
        [lb_score_2 setString:[NSString stringWithFormat:@"Score: %d",currentScore2]];
        
        if (currentRedMark<=2 && currentBlueMark<=2) {
            [self performSelector:@selector(resetGameScreen) withObject:nil afterDelay:3];
        }
        
    }
    if (countRed==7) {
        NSLog(@"red close");
        [self doMarkGame:1];
        stopGame = YES;
        
        currentScore1+=count1*10;
        
        [lb_score_1 setString:[NSString stringWithFormat:@"Score: %d",currentScore1]];
        [lb_score_2 setString:[NSString stringWithFormat:@"Score: %d",currentScore2]];
        
        if (currentRedMark<=2 && currentBlueMark<=2) {
            [self performSelector:@selector(resetGameScreen) withObject:nil afterDelay:3];
        }
    }
    
	float timeStep = 0.03f;
	int32 velocityIterations = 8;
	int32 positionIterations = 8;
	world->Step(timeStep, velocityIterations, positionIterations);
	
	for (b2Body* body = world->GetBodyList(); body != nil; body = body->GetNext())
	{
		BodyNode* bodyNode = (BodyNode*)body->GetUserData();
		if (bodyNode && [bodyNode isKindOfClass:[BodyNode class]] && bodyNode.sprite != nil)
		{
			// update the sprite's position to where their physics bodies are
			bodyNode.sprite.position = [Helper toPixels:body->GetPosition()];
			float angle = body->GetAngle();
			bodyNode.sprite.rotation = -(CC_RADIANS_TO_DEGREES(angle));
		}
        else if ([bodyNode isKindOfClass:[CCNode class]]) {
            CCNode* node = (CCNode*)body->GetUserData();
            if (node) {
                node.position = [Helper toPixels:body->GetPosition()];
                node.rotation = -(CC_RADIANS_TO_DEGREES(body->GetAngle()));
            }
        }
	}
    
    // check collision
    
}

-(BOOL)isInHall:(CGPoint)pos {
    if (pos.x<=0 || pos.x>=1024) {
        return YES;
    }
    if (pos.y<=0 || pos.y>=768) {
        return YES;
    }
    return NO;
}

-(b2World *) getWorld{
    return world;
}

#pragma mark CCTargetedTouchDelegate

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint location = [Helper locationFromTouch:touch];

    for (CCNode* node in [self children]) {
        if ([node isKindOfClass:[Ball class]]) {
            Ball* ball = (Ball*)node;
            if (!ball.isInHall && [ball isTouchForMe:location]) {
                currentTouchTag = ball.tag;
                if (moveFirst==1 && ball.tag<=7) {
                    return [ball ccTouchBegan:touch withEvent:event];
                }
                else if (moveFirst==2 && ball.tag>7) {
                    return [ball ccTouchBegan:touch withEvent:event];
                }
            }
        }
    }
    return NO;
}

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    Ball* mainBall = (Ball*)[self getChildByTag:currentTouchTag];
    [mainBall ccTouchMoved:touch withEvent:event];
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    Ball* mainBall = (Ball*)[self getChildByTag:currentTouchTag];
    [mainBall ccTouchEnded:touch withEvent:event];
}

-(void) autoRedShoot{
    b2Body *red = nil;
    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *tempSprite = (CCSprite *) b->GetUserData();
            if (tempSprite.visible==YES && tempSprite.tag>7) {
                red = b;
                break;
            }
        }        
    }
    b2Body *blue = nil;
    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *tempSprite = (CCSprite *) b->GetUserData();
            if (tempSprite.visible==YES && tempSprite.tag<=7) {
                blue = b;
                break;
            }
        }        
    }
    if (red && blue) {
        b2Vec2 bluePos = blue->GetWorldCenter();
        b2Vec2 redPos = red->GetWorldCenter();
        
        b2Vec2 bodyToMove = bluePos - redPos;
        b2Vec2 force = 1.5 * bodyToMove;

        red->SetLinearVelocity(force);
        red->SetAngularVelocity(0.0f);
    }
    
    redHadShoot = YES;
    
    [self schedule:@selector(checkBallNotMove)];
}

-(BOOL) checkBallNotMove{
    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            if((b->IsAwake()))
            {
                return NO;
            }
        }        
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [[CCDirector sharedDirector] replaceScene:[CCTransitionMoveInL transitionWithDuration:0.5 scene:[MenuGame scene]]];
    }
    else if (buttonIndex==1) {
        currentRedMark = 0;
        currentBlueMark = 0;
        
        [self resetAllBall];
        
        b1.visible = NO;
        b2.visible = NO;
        b3.visible = NO;
        
        br1.visible = NO;
        br2.visible = NO;
        br3.visible = NO;
        
        [lb_score_1 setString:@"Score: 0"];
        [lb_score_2 setString:@"Score: 0"];
        
        currentScore1 = 0;
        currentScore2 = 0;
    }
}

@end
